package szte.objectorgy.collections;

import java.util.EmptyStackException;
import java.util.NoSuchElementException;

import szte.objectorgy.collections.Vector.VectorIterator;

/**
 * Stack data structure (FIFO) with a Vector underlying implementation.
 * 
 * @author Csilla-Andrea KAPUSI
 * @param <T>
 *            The type of the elements stored in this collection.
 */
public class Stack<T extends Comparable<T>> extends Vector<T> {

	public Stack(Class<T> type) {
		super(type);
	}

	public T pop() {
		if (count == 0) {
			throw new EmptyStackException();
		}
		final int index = --count;
		final T obj = (T) elements[index];
		elements[index] = null;
		return obj;
	}

	public void push(T element) {
		add(element);
	}
	
	public Iterator<T> getIterator() {
		return new StackIterator();
	}
	
	public class StackIterator implements Iterator<T> {
		int numLeft = size();
		int lastPosition = -1;

		@Override
		public boolean hasNext() {
			return numLeft > 0;
		}

		@Override
		public T next() {
			try {
				int index = numLeft - 1;
				T result = get(index);
				lastPosition = index;
				numLeft--;
				return result;
			} catch (IndexOutOfBoundsException e) {
				throw new NoSuchElementException();
			}
		}
		
	}
}
